package com.linkage.jz.bankruptcy.activity.Vote;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.Vote.ProVote;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteDetail;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.fragment.Vote.ProVoteDetailFragment_Manager;
import com.linkage.jz.bankruptcy.fragment.Vote.ProVoteDetailRateFragment_Manager;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.widget.CommonPopupMenu;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * 表决详情
 */
public class ProVoteDetailActivity_Manager extends BaseCreateActivity {
    public static final String KEY_ID = "key_id";

    private String mId = "";
    private ProVoteDetail mProVoteDetail;

    private RadioButton radioButton1;
    private RadioButton radioButton2;
    private ViewPager viewPager;
    private ArrayList<Object> items = new ArrayList<>();
    private ProVoteDetailFragment_Manager mDetailFragment;
    private ProVoteDetailRateFragment_Manager mRateFragment;

    private CommonPromptDialog mPromptDialog;

    private boolean editVote = false;
    private boolean deleteVote = false;
    private boolean undoVote = false;

    SwipeRefreshLayout swipeRefreshLayout;

    @Override
    public void initData() {

    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {


    }

    @Override
    public void setListener() {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pro_vote_detail_manager);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mId = getIntent().getStringExtra(KEY_ID);

        mDetailFragment = ProVoteDetailFragment_Manager.newInstance(mId);
        mRateFragment = ProVoteDetailRateFragment_Manager.newInstance(mId);


        RadioGroup radioGroup = findViewById(R.id.radioGroup);
        radioButton1 = findViewById(R.id.radio1);
        radioButton2 = findViewById(R.id.radio2);


        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.radio1:
                    radioButton1.setTextSize(18);
                    radioButton2.setTextSize(16);
                    viewPager.setCurrentItem(0);// 选择某一页
                    break;
                case R.id.radio2:
                    radioButton1.setTextSize(16);
                    radioButton2.setTextSize(18);
                    viewPager.setCurrentItem(1);
                    break;
            }
        });


        FragmentManager fragmentManager = this.getSupportFragmentManager();
        items.add(mDetailFragment);
        items.add(mRateFragment);
        viewPager = findViewById(R.id.viewpager);
        viewPager.setAdapter(new ViewPagerAdapter(fragmentManager, items));
        viewPager.setCurrentItem(0, false);
        viewPager.setOffscreenPageLimit(items.size());
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        radioButton1.setChecked(true);
                        break;
                    case 1:
                        radioButton2.setChecked(true);
                        break;
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                /*RelativeLayout.LayoutParams lp=(RelativeLayout.LayoutParams) tabLine.getLayoutParams();
                //获取组件距离左侧组件的距离
                lp.leftMargin=(int) ((positionOffset+position)*screenWidth/4);
                tabLine.setLayoutParams(lp);*/
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if(state == 1) {
                    swipeRefreshLayout.setEnabled(false);//设置不可触发
                }else if(state == 2){
                    swipeRefreshLayout.setEnabled(true);//设置可触发
                }
            }
        });
        radioButton1.performClick();

        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(() -> getDetail());
        mRateFragment.setSwipeRefreshLayout(swipeRefreshLayout);


    }

    @Override
    public  void onResume() {
        super.onResume();
        getDetail();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_VOTE)) {
            getDetail();
        }
    }


    public class ViewPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Object> items;

        ViewPagerAdapter(FragmentManager fm, ArrayList<Object> items) {
            super(fm);
            this.items = items;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return (Fragment) items.get(position);
                case 1:
                    return (Fragment) items.get(position);
            }
            return (Fragment) items.get(position);

        }

        @Override
        public int getCount() {
            return items.size();
        }

    }

    private CommonPopupMenu popupMenu;

    private void refeshAction() {
        if (mProVoteDetail.getResultStatus() == 1) {
            radioButton2.setText("表决结果");
        } else if (mProVoteDetail.getStatus() == ProVote.STATUS_YJS) {
            if (mProVoteDetail.getResultStatus() == 1) {
                radioButton2.setText("表决结果");
            } else {
                radioButton2.setText("表决进度");
            }
        }

        List<String> menus = new ArrayList<>();
        if (editVote) {
            menus.add("编辑");
        }
        if (deleteVote) {
            menus.add("删除");
        }
        if (undoVote) {
            menus.add("撤销");
        }
        if (menus.size() == 0) {
            titlebar_menu.setVisibility(View.GONE);
            return;
        }
        popupMenu = new CommonPopupMenu(this, menus);
        titlebar_menu.setVisibility(View.VISIBLE);
        titlebar_menu.setOnClickListener(v -> {
            popupMenu.showLocation(R.id.titlebar_menu);// 设置弹出菜单弹出的位置
            popupMenu.setOnItemClickListener((index, str) -> {
                popupMenu.dismiss();
                if (TextUtils.equals(str, "编辑")) {
                    Intent intent = new Intent(ProVoteDetailActivity_Manager.this,
                            ProVoteNewVoteActivity.class);
                    intent.putExtra(ProVoteNewVoteActivity.KEY_ACTION, "edit");
                    intent.putExtra(ProVoteNewVoteActivity.KEY_VOTE, mProVoteDetail);
                    startActivity(intent);
                } else if (TextUtils.equals(str, "删除")) {

                    mPromptDialog = new CommonPromptDialog(ProVoteDetailActivity_Manager.this,
                            CommonPromptDialog.TYPE_TIPS);
                    mPromptDialog.setContent("确定要删除吗?");
                    mPromptDialog.setPositiveClickListener(null, view -> {
                        mPromptDialog.dismiss();
                        deleteVote();
                    });
                    mPromptDialog.setNegativeClickListener(null, view -> mPromptDialog.dismiss());
                    mPromptDialog.show();
                } else if (TextUtils.equals(str, "撤销")) {
                    mPromptDialog = new CommonPromptDialog(ProVoteDetailActivity_Manager.this,
                            CommonPromptDialog.TYPE_EDIT_MULT);
                    mPromptDialog.setTitle("撤销");
                    mPromptDialog.setEditHint("请填写撤销说明");
                    mPromptDialog.setEditMaxLength(60);
                    mPromptDialog.setPositiveClickListener("确定撤销", view -> {
                        String text = mPromptDialog.dialog_prompt_edit.getText().toString().trim();
                        if (TextUtils.isEmpty(text)) {
                            ToastUtil.showShort("请填写撤销说明");
                            return;
                        }
                        mPromptDialog.dismiss();
                        cancelVote(text);
                    });
                    mPromptDialog.setNegativeClickListener(null, view -> mPromptDialog.dismiss());
                    mPromptDialog.show();
                }
            });
        });
    }


    private void getDetail() {
//        showLoading("加载中...");
        Network
                .getAPIService()
                .getVoteDetail(getUserToken(), mId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");
                        editVote = data.getAsJsonObject("auth").get("editVote").getAsBoolean();
                        deleteVote = data.getAsJsonObject("auth").get("deleteVote").getAsBoolean();
                        undoVote = data.getAsJsonObject("auth").get("undoVote").getAsBoolean();
                       Boolean  canNotice = data.get("canNotice").getAsBoolean();

                        mProVoteDetail = ProVoteDetail.parse(data.getAsJsonObject("voteInfo"));
                        mProVoteDetail.setCanNotice(canNotice);
                        mDetailFragment.refreshInfo(mProVoteDetail);
                        mRateFragment.refreshInfo(mProVoteDetail);
                        refeshAction();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                        super.onError(e);
                    }
                });
    }

    @Override
    protected void hideLoading() {
        super.hideLoading();
        swipeRefreshLayout.setRefreshing(false);
    }

    private void deleteVote() {
        showLoading("提交中");
        Network
                .getAPIService()
                .deleteVote_Manager(getUserToken(), mId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_VOTE);
                        EventBus.getDefault().post(event);
                        ToastUtil.showShort("删除成功");
                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                        super.onError(e);
                    }
                });
    }

    private void cancelVote(String content) {
        showLoading("提交中...");
        Network
                .getAPIService()
                .cancelVote_Manager(getUserToken(), mId, content)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        hideLoading();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_VOTE);
                        EventBus.getDefault().post(event);
                        ToastUtil.showShort("撤销成功");
                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                        super.onError(e);
                    }
                });
    }
}
